import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
import store from '@/store'
import { h } from 'vue'

const routes = [
  {
    path: '/',
    name: 'layout',
    component: () => import('../views/layout'),
    children: [
      {
        path: '/',
        component: () => import('../views/home')
      },
      { path: '/category/:id', component: () => import('../views/category') },
      {
        path: '/category/sub/:id',
        component: () => import('../views/category/sub')
      },
      {
        path: '/product/:id',
        component: () => import('../views/goods')
      },
      {
        path: '/cart',
        component: () => import('../views/cart')
      },
      {
        path: '/member',
        component: () => import('../views/member/layout'),
        children: [
          { path: '/member', component: () => import('../views/member/home') },
          // 这种平级写法，无法实现模糊匹配
          // {
          //   path: '/member/order',
          //   component: () => import('../views/member/order')
          // },
          // {
          //   path: '/member/order/:id',
          //   component: () => import('../views/member/order/detail')
          // }
          // vue3.0 需要有嵌套关系才能模糊匹配
          {
            path: '/member/order',
            component: { render: () => h(<RouterView />) },
            children: [
              { path: '', component: () => import('../views/member/order') },
              {
                path: ':id',
                component: () => import('../views/member/order/detail')
              }
            ]
          }
        ]
      },
      {
        path: '/member/checkout',
        component: () => import('../views/member/pay/checkout')
      },
      {
        path: '/member/pay',
        component: () => import('../views/member/pay')
      },
      {
        path: '/pay/callback',
        component: () => import('../views/member/pay/result')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login')
  },
  {
    path: '/login/callback',
    name: 'loginBack',
    component: () => import('../views/login/callback')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior (to, from, savedPosition) {
    return {
      left: 0,
      top: 0
    }
  }
})

router.beforeEach((to, from, next) => {
  const { token } = store.state.user.profile
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })

    return
  }

  next()
})

export default router
